define(["jquery","bbcare"],function($,$bb){
    var servers = {};
    var URL = $bb.baseUrl("followapp");

    /**
	 * 查询历史记录
	 */
	servers.ajaxRecordHistory = function(params,callback){
		$bb.ajax({
            url: URL + "service/evaluation/growth/history",
            data: JSON.stringify({
                data: {
                    "oprInfo": {
                        "channelType": "2"
                    },
                    "queueUserId": params.userId,
                }
            }),
            success: function (data) {
                if(data.success){
                    callback(data,params);
                }else{
                    $bb.toastShow(data.msg ? data.msg : "查询历史记录出错！");
                }
            }
        })
	}

    /**
     * 获取默认历史记录的索引
     */
    servers.getDefaultIndex = function(list,recordId){
        for (var i = 0; i < list.length; i++) {
            if( list[i].recordId == recordId ){
                return i;
            }
        }
        return 0;
    }

    /**
     * 查询患者生长发育记录信息
     */
    servers.ajaxGrowthData = function(params,callback){
        $bb.ajax({
            url: URL + "service/evaluation/getGrowthCurvedata",
            data: JSON.stringify({
                data: {
                    "recordId":params.recordId,
                    'ageType':params.ageType,
                    'scoreType':params.scoreType
                }
            }),
            success: function (data) {
                if(data.success){
                    callback(data.data,params);
                }else{
                    $bb.toastShow(data.msg ? data.msg : "查询患者生长发育记录信息出错！");
                }
            }
        })
    }

    /**
     * 处理基本信息
     */
    servers.handleInfo = function(info){
        var w = parseInt( info.pregnancyDay / 7 );
        var d = Math.round( info.pregnancyDay % 7 );
        info.pregnancyWeek = w + "周" + d + "天";
        return info;
    }

    /**
     * 处理结果
     */
    servers.handleResult = function(data,params){
        var result = data.result;
        var obj = {};
        if( params.ageType == "01" ){ // 纠正年龄
            obj.heightSumary = result.correctHeightsumary;
            obj.heightRange = result.correctHeightrange;
            obj.weightSumary = result.correctWeightsumary;
            obj.weightRange = result.correctWeightrange;
            obj.headSumary = result.correctHeadsumary;
            obj.headRange = result.correctHeadrange;
        }else if( params.ageType == "02" ){ // 实际年龄
            obj.heightSumary = result.heightSumary;
            obj.heightRange = result.heightRange;
            obj.weightSumary = result.weightSumary;
            obj.weightRange = result.weightRange;
            obj.headSumary = result.headSumary;
            obj.headRange = result.headRange;
        }
        obj.height = data.height;
        obj.weight = data.weight;
        obj.headCircumference = data.headCircumference;
        var heightStatus,weightStatus,headStatus;
        switch(obj.heightSumary){
            case "迟缓":
                heightStatus = "2"; // 异常
                break;
            case "下":
                heightStatus = "1"; // 可疑
                break;
            default:
                heightStatus = "0"; // 正常
                break;
        };
        switch(obj.weightSumary){
            case "超重":
            case "消瘦":
                weightStatus = "2"; // 异常
                break;
            case "上":
            case "上-":
            case "下":
                weightStatus = "1"; // 可疑
                break;
            default:
                weightStatus = "0"; // 正常
                break;
        };
        switch(obj.headSumary){
            case "偏大":
            case "偏小":
                headStatus = "2";   // 异常
                break;
            case "上":
            case "上-":
            case "下":
                headStatus = "1";  // 可疑
                break;
            default:
                headStatus = "0";  // 正常
                break;
        };
        if( !obj.heightSumary ) obj.heightSumary = "无数据";
        if( !obj.weightSumary ) obj.weightSumary = "无数据";
        if( !obj.headSumary ) obj.headSumary = "无数据";
        obj.heightStatus = heightStatus;
        obj.weightStatus = weightStatus;
        obj.headStatus = headStatus;
        if( obj.heightStatus == "2" || obj.weightStatus == "2" || obj.headStatus == "2"){
            obj.wLStatus = "2";
            obj.wLSumary = "异常";
        }else if( obj.heightStatus == "1" || obj.weightStatus == "1" || obj.headStatus == "1"){
            obj.wLStatus = "1";
            obj.wLSumary = "可疑";
        }else{
            obj.wLStatus = "0";
            obj.wLSumary = "正常";
        }
        return {
            "result":obj,
            "curveType":data.curveType,
            "userInfo":data.userInfo,
            "curvadataList":data.curvadataList,
            "scoreType":data.scoreType,
            "guideDetails":data.guideDetails,
        };
    }

    /**
     * 查询指导意见、备注
     */
    servers.ajaxGuide = function(params,callback,datas){
        $bb.ajax({
            url: URL + "service/evaluation/getGuide",
            data: JSON.stringify({
                data: {
                    "examinationPaperName":"GROWTH",
                    "channelType":"2",
                    "queueUserId":params.userId,
                    "evaluationId":params.recordId,
                }
            }),
            success: function (data) {
                if(data.success){
                    callback(data.data,params,datas);
                }else{
                    $bb.toastShow(data.msg ? data.msg : "查询指导意见、备注出错！");
                }
            }
        })
    }

    /**
     * 修改指导意见、备注
     */
    servers.ajaxModifyGuides = function(params,callback){
        var channelId = $bb.getChannelId();
        $bb.ajax({
            url: URL + "service/evaluation/guidemodify",
            data: JSON.stringify({
                data: {
                    "channelType":"2",
                    "channelId":channelId,
                    "examinationPaperName":"GROWTH",
                    "evaluationId":params.recordId,
                    "queueUserId":params.userId,
                    "guide":params.guide,
                    "remark":params.remark,
                }
           }),
           success: function (data) {
                if(data.success){
                    callback(data.data,params);
                }else{
                    $bb.toastShow(data.msg ? data.msg : "修改指导意见、备注出错！");
                }
           }
        });
    }

    //孕周
    servers.toPregnancyDay=function(day){
        var days = day * 7;
        var w = parseInt( days / 7 );
        var d = Math.round( days % 7 );
        return w+"周"+d+"天"
    }

    //周
    var toWeekDay=function(week){
        var w=parseInt(week);//获得周
        var d=Math.round((week-w)*7);//获得天
        var age;
        w? age=w+"周"+(d?(d+"天"):''):age=d+"天";
        return age
    };
    //月：
    var toMonthDay=function (month){
        var m=parseInt(month);//获得月份；
        var w=parseInt((month-m)*30.4/7);//获得周
        var d=Math.round((month-m)*30.4%7);//获得天
        var age;
        m? age=m+"月"+(w? w+"周":"")+(d? d+"天":""):age=(w? w+"周":"")+(d? d+"天":"");
        return age
    }
    //岁：
    var toYearDay=function(year){
        var y=parseInt(year);//获得年份；
        var m=parseInt((year-y)*365/30.4);//获得月份；
        var w=parseInt(((year-y)*365%30.4)/7);//获得周
        var d=Math.round(((year-y)*365/30.4)%7);//获得天
        var age;
        y?age=y+"岁"+(m? m+"月":"")+(w? w+"周":"")+(d?d+"天":""):age=(m?m+"月":"")+(w? w+"周":"")+(d?d+"天":"");
        return age
    };
    servers.babyAgeDeal=function(res,age){
        var babyAge;
        if(res.timeUnit=="周"){
            babyAge = toWeekDay(age);
        }
        if(res.timeUnit=="月"){
            babyAge = toMonthDay(age);
        }
        if(res.timeUnit=="年"){
            babyAge = toYearDay(age);
        }
        return babyAge;
    };

    //儿童传入记录值数据处理：
    var growthRecordDeal=function(data){
        var type=data.type;
        var sexColor;
        var color=["#0596d5","#e47db2","#ff8400"];//0,男；1，女；3，橙色
        var initArr={
            "history":[],
            'nowFlag':[]
        };
        var growthRecordVal=data.growthrecord;
        for(var i=0;i<growthRecordVal.length;i++){
            if(growthRecordVal[i].result) {
                var growthResult = typeof growthRecordVal[i].result == "string" ? JSON.parse(growthRecordVal[i].result) : growthRecordVal[i].result;
                var result, first, last;
                if (data.scoreType == "01") {
                    result = growthResult.result;
                    if(data.curveType == "02"){
                       if (result && result.indexOf("~") != "-1") {
                           sexColor = data.sex == "F" ? color[1] : color[0];
                       }else{
                           sexColor = color[2];
                       }
                    }else{
                       if (result && result.indexOf("~") != "-1") {
                           first = parseFloat(result.substring(0, result.indexOf("~") - 1));
                           last = parseFloat(result.substring(result.indexOf("~") + 1, result.length - 1));
                           if (type == "weight" || type == "wl") {
                               if (!(first >= 25 && last <= 75)) {
                                   sexColor = color[2];
                               } else {
                                   sexColor = data.sex == "F" ? color[1] : color[0];
                               }
                           } else if (type == "height" || type == "head") {
                               if (first < 25) {
                                   sexColor = color[2];
                               } else {
                                   sexColor = data.sex == "F" ? color[1] : color[0];
                               }
                           }
                       } else {
                           if (result && result.indexOf("<") != "-1") {
                               sexColor = color[2];
                           } else if (result && result.indexOf(">") != "-1") {
                               if (type == "weight" || type == "wl") {
                                   sexColor = color[2];
                               } else if (type == "height" || type == "head") {
                                   sexColor = data.sex == "F" ? color[1] : color[0];
                               }
                           }
                       }
                   }
                } else {
                    result = growthResult.result;
                    if (result && result.indexOf("~") != "-1") {
                        first = parseFloat(result.substring(0, result.indexOf("~")));
                        last = parseFloat(result.substring(result.indexOf("~") + 1, result.length));
                        if(first>= -2 && last <= 2){
                            sexColor = data.sex == "F" ? color[1] : color[0];
                        }else{
                            sexColor = color[2];
                        }
                    } else {
                        if (result && result.indexOf("<") != "-1" || result && result.indexOf(">") != "-1") {
                            sexColor = color[2];
                        }
                    }
                }
            }
            var recentGrowthRecord2={
                value: [growthRecordVal[i].xDate,growthRecordVal[i].yDate],
                itemStyle: {
                    normal:{
                        color:sexColor
                    },
                    emphasis: {
                        color: sexColor
                    }
                }
            };
            if(growthRecordVal[i].flag=="1"){
                initArr.nowFlag = [growthRecordVal[i].xDate,growthRecordVal[i].yDate,sexColor];
            }
            initArr.history.push(recentGrowthRecord2);
        }
        return initArr;
    };

    //曲线数据处理
    var dataDo=function(data,max,min,name,color){
        var lens=data.length;
        var res=[];
        min=Number(min);
        len=(max-min)/lens;
        res[0]=[min,data[0]];
        for(i= 0;i<lens;i++){
            if(i==lens-1){
                var lastData={
                    value: [len*(i+1)+min,data[i]],
                    label : {
                        normal:{
                            show: true,
                            position: "insideBottomLeft",
                            textStyle : {
                                color:color,
                                fontSize:"8"
                            },
                            formatter:name
                        }
                    },
                };
                res.push(lastData);
            }else{
                res[i+1]=[len*(i+1)+min,data[i]];
            }
        }
        return res;
    };

    /**
     * 图标数据格式处理
     */
    servers.dataDo2=function(data){
        var obj={};
        obj.xMax=data.xMax;
        obj.xMin=data.xMin;
        obj.yMax=data.yMax;
        obj.yMin=data.yMin;
        obj.scoreType=data.scoreType;
        if((obj.yMax-obj.yMin)>60){
            obj.interval=5;
        }else if((obj.yMax-obj.yMin)<=25){
            obj.interval=1;
        }else{
            obj.interval=2;
        }
        var name;
        if(obj.scoreType == "01"){
            name=["50%","25%","75%","10%","90%","3%","97%"];
        }else{
            name=["0","-1","1","-2","2","-3","3"];
        }
        var colors = ['#00612d','#ffb13d','#e41836','#252122'];//0--SD0,1--SD1,SD1neg,2--SD2,SD2neg,3--SD3,SD3neg
        if(data.SD0){
            obj.sd0={
                "num":0,
                "name":name[0],
                "sd0":dataDo(data.SD0, data.xMax, data.xMin,name[0],colors[0])
            };
        }
        if(data.SD1){
            obj.sd1={
                "num":1,
                "name":name[2],
                "sd1":dataDo(data.SD1, data.xMax, data.xMin,name[2],colors[1])
            };
        }
        if(data.SD1eng){
            obj.sd1neg={
                "num":1,
                "name":name[1],
                "sd1neg":dataDo(data.SD1eng, data.xMax, data.xMin,name[1],colors[1])
            };
        }
        if(data.SD2){
            obj.sd2={
               "num":2,
               "name":name[4],
               "sd2":dataDo(data.SD2, data.xMax, data.xMin,name[4],colors[2])
            };
       }
        if(data.SD2eng){
            obj.sd2neg={
                "num":2,
                "name":name[3],
                "sd2neg":dataDo(data.SD2eng, data.xMax, data.xMin,name[3],colors[2])
            };
        }
        if(data.SD3){
            obj.sd3={
                "num":3,
                "name":name[6],
                "sd3":dataDo(data.SD3, data.xMax, data.xMin,name[6],colors[3])
            };
        }
        if(data.SD3eng){
           obj.sd3neg={
               "num":3,
               "name":name[5],
               "sd3neg":dataDo(data.SD3eng, data.xMax, data.xMin,name[5],colors[3])
           };
        }
        //儿童记录：
        var backData=growthRecordDeal(data);
        obj.grownRecord=backData.history;
        obj.grownNowRecord=backData.nowFlag;
        if(data.timeUnit=="周"){
            obj.xName="周龄（0-26周)";
        }else if(data.timeUnit=="月"){
            obj.xName="月龄（0-24月)";
        }else if(data.timeUnit=="年"){
            obj.xName="年龄（0-5岁)";
        }
        obj.timeUnit=data.timeUnit;
        return obj;
    };

    //儿童传入记录值数据处理：
    var trendsNameDeal=function(data,name,trendname,color){
        var len=data.length;
        data[len-24]={
            value: data[len-24],
            label : {
                normal:{
                    show: true,
                    position: "insideRight",
                    textStyle : {
                        color:color,
                        fontSize:"9"
                    },
                    formatter:name
                }
            },
        }
        if(name=="97%" || name=="3"){
            data[len-55]={
                value: data[len-55],
                label : {
                    normal:{
                        show: true,
                        position: 'top',
                        textStyle : {
                            color:"#aaa",
                            fontSize:"8"
                        },
                        formatter:trendname
                    }
                },
            }
        }
        return data;
    }

    /**
     * fenton曲线数据处理
     */
    servers.fentonDeal=function(data,sexColor,gender){
        var fentonRes={};
        var keyName=["weight","height","head",'baby'];
        var keyName2,lineType,lineColor;
        if(data.scoreType == "01"){
            keyName2=['50%','10%','90%','3%','97%','baby'];
            lineType=['solid','dashed','dashed','dotted','dotted'];
           // lineColor=['black','black','black','black','black'];
            lineColor=['#00612d','#00b0c8','#00b0c8','#ff8400','#ff8400'];
            for(var i=0;i<data.curvadataList.length;i++){
                if(data.curvadataList[i].type=='0000'+(i+1)){
                    fentonRes[keyName[i]]=[];
                    fentonRes[keyName[i]][0] = data.curvadataList[i].curvedata.SD0,
                    fentonRes[keyName[i]][1] = data.curvadataList[i].curvedata.SD2eng,
                    fentonRes[keyName[i]][2] = data.curvadataList[i].curvedata.SD2,
                    fentonRes[keyName[i]][3] = data.curvadataList[i].curvedata.SD3eng,
                    fentonRes[keyName[i]][4] = data.curvadataList[i].curvedata.SD3,
                    fentonRes[keyName[i]][5] = data.curvadataList[i].curvedata.growthrecord
                }
            }
        }else if(data.scoreType == "02"){
            keyName2=['0','-1','1','-2','2','-3','3','baby'];
            lineType=['solid','solid','solid','solid','solid','solid','solid'];
            lineColor=['#00612d','#ffb13d','#ffb13d','#e41836','#e41836','#252122','#252122'];//0--SD0,1--SD1,SD1neg,2--SD2,SD2neg,3--SD3,SD3neg
            for(var i=0;i<data.curvadataList.length;i++){
                if(data.curvadataList[i].type=='0000'+(i+1)){
                    fentonRes[keyName[i]]=[];
                    fentonRes[keyName[i]][0] = data.curvadataList[i].curvedata.SD0,
                    fentonRes[keyName[i]][1] = data.curvadataList[i].curvedata.SD1eng,
                    fentonRes[keyName[i]][2] = data.curvadataList[i].curvedata.SD1,
                    fentonRes[keyName[i]][3] = data.curvadataList[i].curvedata.SD2eng,
                    fentonRes[keyName[i]][4] = data.curvadataList[i].curvedata.SD2,
                    fentonRes[keyName[i]][5] = data.curvadataList[i].curvedata.SD3eng,
                    fentonRes[keyName[i]][6] = data.curvadataList[i].curvedata.SD3,
                    fentonRes[keyName[i]][7] = data.curvadataList[i].curvedata.growthrecord
                }
            }
        }
        var series=[];
        for(var item in fentonRes){
            var name,yAxisIndex,trendName,type;
            item =='height' ? name="身长":item=='weight'? name="体重" :item=='head'?name="头围":name="baby";
            item =='height' ? trendName="身长":item=='weight'? trendName="体重" : item=='head'?trendName="头围":trendName="baby";
            item =='weight'? yAxisIndex=0:yAxisIndex=1;
            item =='weight'? type="weight":item =='height'? type="height":type="head";
            for( var i=0;i<fentonRes[item].length;i++){
                if(i==fentonRes[item].length-1){
                    var growthData={
                        'growthrecord':fentonRes[item][i],
                        'type':type,
                        'sex':gender,
                        'scoreType':data.scoreType,
                        'curveType':data.curveType
                    }
                    var babyInit= growthRecordDeal(growthData);
                    babyInit.nowFlag[1] =  item == "weight" ? parseFloat(babyInit.nowFlag[1]).toFixed(2) : parseFloat(babyInit.nowFlag[1]).toFixed(1);
                    var baby={};
                    baby={
                        name: name,
                        type: 'line',
                        data:babyInit.history,
                        symbol:'circle',
                        symbolSize:'6',
                        markPoint: {
                            itemStyle: {
                                normal: {
                                    color:babyInit.nowFlag[2]
                                }
                            },
                            data: [
                                {
                                    xAxis: babyInit.nowFlag[0],
                                    yAxis: babyInit.nowFlag[1]
                                }
                            ]
                        },
                        itemStyle: {
                            normal: {
                                color: sexColor,
                                lineStyle: {
                                    width:1
                                }
                            },
                            emphasis:{
                                color:sexColor
                            }
                        },
                        yAxisIndex:yAxisIndex
                    }
                    series.push(baby);
                }else{
                    fentonRes[item][i]=trendsNameDeal(fentonRes[item][i],keyName2[i],trendName,lineColor[i]);
                    var trend= {
                        name: keyName2[i],
                        type: 'line',
                        smooth:"true",
                        symbol:'circle',
                        hoverAnimation:false,
                        itemStyle: {
                            normal: {
                                color: "transparent",
                                lineStyle: {
                                    color:lineColor[i],
                                    type:lineType[i],
                                    width:1
                                }
                            }
                        },
                        data: fentonRes[item][i],
                        yAxisIndex:yAxisIndex
                    }
                    series.push(trend);
                }
            }
        }
        series.push({
            type: 'line',
            symbol:'none',
            hoverAnimation:false,
            itemStyle: {
                normal: {
                    lineStyle: {
                        color:"#333",
                        width:2
                    }
                }
            },
            data: [[40,-30],[40,60]],
            yAxisIndex:1
        });
        return series;
    }

    /**
     * 获取单位（获取图里的x、y轴上的单位）
     */
    servers.getUnit = function(str){
        var unit = str.split("(")[1].split(")")[0];
        if (unit == "g") unit = "kg";
        return unit;
    }

    return servers;
});